package com.yh.gulimall.product.web;

import com.yh.gulimall.product.entity.CategoryEntity;
import com.yh.gulimall.product.service.CategoryService;
import com.yh.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        // TODO 1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntities);
        return "index";
    }


    /**
     * 获取二级分类
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1.获取一把锁、只要锁的名字一样就是用一把锁。（可重入）
        RLock lock = redissonClient.getLock("my-lock");

        //2、加锁
//        lock.lock();
        //十秒钟自动解锁（我们业务是30s，当运行到11s时。会将锁删除，别人进行占用的情况吗？）
        //结论：当设置10s过期时间。会出现上述问题，看门狗不会续期。
        lock.lock(10, TimeUnit.SECONDS);

        try {
            System.out.println(Thread.currentThread()+"加锁成功，执行业务");
            Thread.sleep(30000);
        } catch (Exception e) {

        } finally {
            //3、解锁  假设断电解锁代码没有运行，redisson会不会出现死锁
            System.out.println(Thread.currentThread()+"释放锁");
            lock.unlock();
        }
        return "hello";
    }

    //保证一定能读到最新的数据，修改期间，写锁是一个排它锁（互斥锁）。读锁是一个共享锁
    //写锁没释放读就必须等待
    //读+读：相当于无锁。同时加锁
    //写+读：等待写锁释放
    //写+写：阻塞
    //读+写：有读锁，写需要等待
    @GetMapping(value = "/write")
    @ResponseBody
    public String writeValue() {
        String s = "";
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.writeLock();
        try {
            //1、改数据加写锁，读数据加读锁
            rLock.lock();
            System.out.println("写锁加锁成功"+Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            ops.set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("写锁释放成功"+Thread.currentThread().getId());
        }

        return s;
    }

    @GetMapping(value = "/read")
    @ResponseBody
    public String readValue() {
        String s = "";
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        //加读锁
        RLock rLock = readWriteLock.readLock();
        try {
            rLock.lock();
            System.out.println("读锁加锁成功"+Thread.currentThread().getId());

            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            s = ops.get("writeValue");
            Thread.sleep(30000);
//            try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("读锁释放成功"+Thread.currentThread().getId());
        }
        return s;
    }


    /**
     * 测试信号量
     * 车库停车
     * 3个车位
     * 当park3次车位剩余量为0，再次park会阻塞。直到go。
     */
    @GetMapping("/park")
    @ResponseBody
    public String park(){
        RSemaphore park = redissonClient.getSemaphore("park");
        //获取一个信号-》占一个车位
        boolean b=false;
        try {
//            park.acquire();//阻塞式获取，一定要获取到一个车位
             b= park.tryAcquire();//尝试获取，有了就停，没有就算了
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "ok=》"+b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore park = redissonClient.getSemaphore("park");
        //释放一个信号-》空闲一个车位
        park.release();
        return "ok";
    }


    /**
     * 放假锁门
     * 1班没人了，2班没人了...
     * 和JUC一样的
     * 5个班全部走完，锁门
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor(){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        try {
            door.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "放假了！";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();
        return id+"班的人走完了";
    }

}
